<?php
    /**
     * Created by PhpStorm.
     * User: mybook-lhp
     * Date: 18/9/19
     * Time: 下午4:53
     */

    namespace app\member\model;


    use app\base\model\Transfer;
    use app\base\model\WalletProductModel;
    use app\common\utils\UtilTree;
    use app\face2market\model\Face2marketRecommendRewardMsgModel;
    use app\face2market\model\RegisterShareLogModel;
    use app\face2market\model\ReleaseLockLogModel;
    use app\face2market\model\WalletProductLockModel;
    use app\payment\model\WalletModel;
    use app\share\model\ShareLogModel;
    use think\Db;
    use think\Model;

    class CheckPresentDataModel extends Model
    {

        protected $name = 'face2market_check_member';

        // 自动写入时间戳
        protected $autoWriteTimestamp = true;

        protected $dateFormat = 'Y/m/d H:s';

        /**
         * 用户资产是否正常
         */
        static public function check_data($where = [],$str,$end)
        {


            $MemberModel = MemberModel::where($where)->select();

            foreach ($MemberModel as $Member)
            {
                //获取之前的信息
                $member_diffe = self::where(['member_id' => $Member['id']])->find();

                //获取当天的所有的信息 充值 买卖 提现 余额 转赠 分享 商城
                $query_data = static::query_data($Member['id'],$str,$end);

                //计算金额 ：充值金额 - 挂单买入金额+ 用户交易卖出金额-用户交易买入金额 -提现金额 - 钱包余额 =0
                $money_result = ($query_data['get_member_topup']//
                    - $query_data['get_order_limit']['buy_money']//
                    + $query_data['get_face2market_order']['seller_money']//
                    - $query_data['get_face2market_order']['buy_money']//
                    - $query_data['get_withdraw']//
                    - $query_data['get_payment_wallet']['money']);//
                //计算树 ： 买入树+挂出得树 - 卖出树-资产包树+分享得树(分享人买入奖励+分享奖励+注册奖励)=0
                $product_num_result = round(//
                    $query_data['get_base_wallet_product']//总资产
                    - $query_data['get_payment_wallet_lock']//锁仓
                    + $query_data['product_circulation']['product_out']//转出
                    - $query_data['product_circulation']['product_in']//转入
                    - $query_data['get_face2market_order']['buy_pro']//买入
                    - ($query_data['get_shareReward']['number'])//分享
                    + ceil($query_data['get_face2market_order']['seller_pro'] * 1.1)//卖出
                    + floor($query_data['get_order_limit']['residue_number'] * 1.1)//挂单卖出
                    //                    - ($query_data['register_share_log']['register_obtain_num']//注册
                    //                        + $query_data['register_share_log']['share_obtain_num'])//分享

                    ,2);

                $data['money_result']       = $money_result;
                $data['product_num_result'] = $product_num_result;
                $data['data']               = json_encode($query_data);
                if ($member_diffe)
                {
                    static::update_log($member_diffe['id'],$data);
                }
                else
                {
                    $data['member_id'] = $Member['id'];
                    static::create_log($data);
                }
            }
            return $data;
        }

        /**
         * 查询用户数据
         */
        static public function query_data($member,$str,$end)
        {

            $data = [];

            //获取当天的所有的信息 充值 买卖 提现 余额 转赠 分享 商城

            //获取当天充值
            $get_member_topup = static::get_member_topup($member,$str,$end);

            //获取当天挂单数据
            $get_order_limit = static::get_order_limit($member,$str,$end);

            //获取当天的用户资产
            $get_base_wallet_product = static::get_base_wallet_product($member);

            //获取当天的用户钱包
            $get_payment_wallet = static::get_payment_wallet($member);

            //锁仓资产
            $get_payment_wallet_lock = static::get_base_wallet_product_lock($member);


            //获取当天的用户交易信息
            $get_face2market_order = static::get_face2market_order($member,$str,$end);

            //获取当天的用户提现信息
            $get_withdraw = static::get_withdraw($member,$str,$end);

            //获取用户当天的分享奖励
            $get_shareReward = static::get_shareReward($member,$str,$end);

            //注册奖励
            //            $register_share_log = static::get_register_share_log($member,$str,$end);

            //转入转出
            $product_circulation = static::get_product_circulation($member,$str,$end);

            $data['get_member_topup']        = $get_member_topup;
            $data['get_order_limit']         = $get_order_limit;
            $data['get_base_wallet_product'] = $get_base_wallet_product;
            $data['get_payment_wallet_lock'] = $get_payment_wallet_lock;
            $data['get_payment_wallet']      = $get_payment_wallet;
            $data['get_face2market_order']   = $get_face2market_order;
            $data['get_withdraw']            = $get_withdraw;
            $data['get_shareReward']         = $get_shareReward;
            //            $data['register_share_log']      = $register_share_log;
            $data['product_circulation'] = $product_circulation;

            return $data;
        }

        /**
         * 获取用户充值
         *
         * @param $id
         *
         * @return array|false|\PDOStatement|string|Model
         */
        static public function get_member_topup($id,$str,$end)
        {


            $amount = Db::name('payment_pay')->where([
                'member_id'   => $id,
                'status'      => 1,
                'create_time' => ['between',"$str,$end"]
            ])->sum('money');


            return $amount > 0 ? $amount : 0;
        }

        /**
         *  获取用户挂单
         *
         * @param $id
         *
         * @return mixed
         */
        static public function get_order_limit($id,$str,$end)
        {

            $buy_money      = Db::name('face2market_order_limit')->where([
                'member_id' => $id,
                'status'    => 0,
                //                'create_time' => ['between',"$str,$end"]
            ])->field('(residue_number * price) as buy_money')->find()['buy_money'];
            $residue_number = Db::name('face2market_order_limit')->where([
                'member_id' => $id,
                'status'    => 1,
                //                'create_time' => ['between',"$str,$end"]
            ])->sum('residue_number');


            $data['buy_money']      = $buy_money > 0 ? $buy_money : 0;
            $data['residue_number'] = $residue_number > 0 ? $residue_number : 0;
            return $data;
        }

        /**
         * 用户资产
         *
         * @param $id
         *
         * @return mixed
         */
        static public function get_base_wallet_product($id)
        {

            $product_num        = 0;
            $WalletProductModel = WalletProductModel::where(['member_id' => $id])->select();
            foreach ($WalletProductModel as $key => $item)
            {
                if ($item['product_id'] == 3)
                {
                    $item['product_num'] = round($item['product_num'] / 100,2);
                }
                $product_num += $item['product_num'];

            }
            return round($product_num,2);
        }

        static public function get_base_wallet_product_lock($id)
        {


            $WalletModel = ReleaseLockLogModel::where([
                'member_id' => $id,
            ])->field('num')->find();

            $data = intval($WalletModel['num']) > 0 ? intval($WalletModel['num']) : 0;
            return $data;
        }

        /**
         * 获取用户钱包
         *
         * @param $id
         *
         * @return array
         */
        static public function get_payment_wallet($id)
        {


            $WalletModel   = WalletModel::where(['member_id' => $id])->field('money,point')->find();
            $data['money'] = $WalletModel['money'] > 0 ? $WalletModel['money'] : 0;
            $data['point'] = $WalletModel['point'] > 0 ? $WalletModel['point'] : 0;
            return $data;
        }

        /**
         * 用户交易记录
         *
         * @param $id
         *
         * @return mixed
         */
        static public function get_face2market_order($id,$str,$end)
        {


            $buy_pro      = Db::name('face2market_order')->where([
                'buyer_id'    => $id,
                'status'      => 1,
                'create_time' => ['between',"$str,$end"],
                'del'         => 0
            ])->sum('number');
            $buy_money    = Db::name('face2market_order')->where([
                'buyer_id'    => $id,
                'status'      => 1,
                'create_time' => ['between',"$str,$end"],
                'del'         => 0
            ])->sum('amount');
            $seller_pro   = Db::name('face2market_order')->where([
                'seller_id'   => $id,
                'status'      => 1,
                'create_time' => ['between',"$str,$end"],
                'del'         => 0
            ])->sum('number');
            $seller_money = Db::name('face2market_order')->where([
                'seller_id'   => $id,
                'status'      => 1,
                'create_time' => ['between',"$str,$end"],
                'del'         => 0
            ])->sum('amount');

            $data['buy_pro']      = $buy_pro > 0 ? $buy_pro : 0;
            $data['buy_money']    = $buy_money > 0 ? $buy_money : 0;
            $data['seller_pro']   = $seller_pro > 0 ? $seller_pro : 0;
            $data['seller_money'] = $seller_money > 0 ? $seller_money : 0;
            return $data;
        }

        /**
         * 用户提现
         *
         * @param $id
         *
         * @return mixed
         */
        static public function get_withdraw($id,$str,$end)
        {

            $up_amount_money = Db::name('payment_withdraw')->where([
                'member_id'   => $id,
                'create_time' => ['between',"$str,$end"]
            ])->whereIn('status',[
                0,
                2,
                4
            ])->sum('up_amount_money');


            return $up_amount_money > 0 ? $up_amount_money : 0;
        }

        /**
         * 分享
         *
         * @param $id
         *
         * @return mixed
         */
        static public function get_shareReward($id,$str,$end)
        {

            $RegisterShareLogModel = RegisterShareLogModel::where(['member_id_puid' => $id])->where([
                'create_time' => [
                    'between',
                    "$str,$end"
                ]
            ])->field('sum(share_obtain_num) as reward')->find();
            $register_obtain_num   = RegisterShareLogModel::where(['member_id' => $id])->where([
                'create_time' => [
                    'between',
                    "$str,$end"
                ]
            ])//
//            ->field('sum(register_obtain_num) as register_obtain')//
            ->find();
            echo json_encode([$register_obtain_num]);
//            exit;
            $MemberModel = MemberModel::field('count(id) as num')->where(['phone_puid' => $id])->find();

            $buy_num          = Face2marketRecommendRewardMsgModel::group('member_id')->where([
                'puid'              => $id,
                'reward_pid_status' => 1,
                'create_time'       => ['between',"$str,$end"]
            ])->count();
            $rewards          = Face2marketRecommendRewardMsgModel::where([
                'puid'              => $id,
                'reward_pid_status' => 1,
                'create_time'       => ['between',"$str,$end"]
            ])->sum('reward_tree');
            $buy_reward_refer = ShareLogModel::where(['rewarder_id' => $id])->field('sum(reward_number) as reward_number')->find();
            $reward_number    = $buy_reward_refer['reward_number'] > 0 ? $buy_reward_refer['reward_number'] : 0;

            $rewards               = ($rewards / 100) > 0 ? ($rewards / 100) : 0;
            $reward                = $RegisterShareLogModel['reward'] > 0 ? ($RegisterShareLogModel['reward'] / 100) : 0;
            $register_obtain       = $register_obtain_num['register_obtain'] > 0 ? ($RegisterShareLogModel['register_obtain'] / 100) : 0;
            $buy_num               = $buy_num > 0 ? $buy_num : 0;
            $data['num']           = $MemberModel['num'] > 0 ? $MemberModel['num'] : 0;
            $data['reward']        = '购买' . $rewards . '+分享：' . $reward . '=' . ($reward + $rewards);
            $data['buy_reward']    = $rewards;
            $data['share_reward']  = $reward;
            $data['buy_num']       = $buy_num;
            $data['reward_number'] = $reward_number;
            $data['number']        = $reward_number + $rewards + $reward + $register_obtain;

            return $data;
        }

        /**
         * 注册奖励
         *
         * @param $id
         * @param $str
         * @param $end
         *
         * @return mixed
         */
        static public function get_register_share_log($id,$str,$end)
        {

            //注册人奖励
            $register_obtain_num = RegisterShareLogModel::field('sum(register_obtain_num) as register_obtain_num')->where([
                'member_id'   => $id,
                'create_time' => [
                    'between',
                    "$str,$end"
                ]
            ])->find();
            //推荐人奖励
            $share_obtain_num            = RegisterShareLogModel::field('sum(share_obtain_num) as share_obtain_num')->where([
                'member_id_puid' => $id,
                'create_time'    => [
                    'between',
                    "$str,$end"
                ]
            ])->find();
            $data['register_obtain_num'] = $register_obtain_num['register_obtain_num'] > 0 ? $register_obtain_num['register_obtain_num'] / 100 : 0;
            $data['share_obtain_num']    = $share_obtain_num['share_obtain_num'] > 0 ? $share_obtain_num['share_obtain_num'] / 100 : 0;
            return $data;
        }

        /**
         * 创建日志
         *
         * @param $data
         *
         * @return $this
         */
        static public function create_log($data)
        {

            return self::create($data);
        }

        /**
         * 更新日志
         *
         * @param $id
         * @param $data
         *
         * @return $this
         */
        static public function update_log($id,$data)
        {

            return self::where(['id' => $id])->update($data);
        }

        /**
         * 转入转出
         *
         * @param $id
         * @param $data
         *
         * @return $this
         */
        static public function get_product_circulation($id,$str,$end)
        {

            $product_out = Transfer::where([
                'send_member_id' => $id,
                'create_time'    => [
                    'between',
                    "$str,$end"
                ]
            ])->field('sum(send_number) as send_number,sum(transfer_proc) as transfer_proc')->find();

            $product_in          = Transfer::where([
                'receive_member_id' => $id,
                'create_time'       => [
                    'between',
                    "$str,$end"
                ]
            ])->field('sum(send_number) as send_number')->find();
            $data['product_out'] = ($product_out['send_number'] + $product_out['transfer_proc']) > 0 ? ($product_out['send_number'] + $product_out['transfer_proc']) : 0;
            $data['product_in']  = $product_in['send_number'] > 0 ? $product_in['send_number'] : 0;
            return $data;
        }

    }